#pragma once
#ifndef TEMPLATED_VECTOR_MAP_MANAGER_H
#define TEMPLATED_VECTOR_MAP_MANAGER_H
#include "Base.h"
#include <map>
#include <string>

template<class T>
class CTemplatedVectorMapManager
	{
	public:
		class CMapResourceValue
		{
			public:
				T *m_Value;
				size_t m_Id;
				CMapResourceValue(T *Value, size_t Id): m_Value(Value), m_Id(Id){}
		};
		typedef std::vector<T *> TVectorResources;
		typedef std::map<std::string, CMapResourceValue> TMapResources;
	protected:
		TVectorResources m_ResourcesVector;
		TMapResources m_ResourcesMap;
	public:
		CTemplatedVectorMapManager(){}
		virtual ~CTemplatedVectorMapManager()
		{
			Destroy();
		}
		void RemoveResource(const std::string &Name)
		{
			TMapResources::iterator it = m_ResourcesMap.find(Name);

			if(it!=m_ResourcesMap.end())
			{
				size_t l_Id = it->second.m_Id;
				CHECKED_DELETE(it->second.m_Value);
				m_ResourcesMap.erase(it);
				m_ResourcesVector.erase(m_ResourcesVector.begin()+l_Id);
				for (TMapResources::iterator it1=m_ResourcesMap.begin(); it1!=m_ResourcesMap.end(); ++it1)
				{
					if(it1->second->m_Id>l_Id)
					{
						--it1->second.m_Id;
					}
				}
			} else {
   				LOGGER->AddNewLog(ELL_ERROR, "TemplateVectorManager: Error no existe en el mapa");
			}
		}
		virtual T * GetResourceById(size_t Id)
		{
			if (Id<m_ResourcesVector.size())
			{
				return m_ResourcesVector[Id];
			}
			LOGGER->AddNewLog(ELL_ERROR, "TemplateVectorManager: Error no existe en el mapa");
			return NULL;
		}
		virtual T * GetResource(const std::string &Name)
		{
			TMapResources::iterator it = m_ResourcesMap.find(Name);

			if(it==m_ResourcesMap.end())
			{
   				LOGGER->AddNewLog(ELL_ERROR, "TemplateVectorManager: Error no existe en el mapa");
				return NULL;
			}
			return it->second.m_Value;
		}
		virtual bool AddResource(const std::string &Name, T *Resource)
		{
			TMapResources::iterator it = m_ResourcesMap.find(Name);

			if(it!=m_ResourcesMap.end())
			{
   				LOGGER->AddNewLog(ELL_ERROR, "TemplateVectorManager: Error ya existe en el mapa");
				return false;
			} else {
				m_ResourcesVector.push_back(Resource);
				m_ResourcesMap[Name]=CMapResourceValue(Resource,m_ResourcesVector.size()-1);
				return true;
			}

		}
		virtual void Destroy()
		{
			for (int i=0; i<m_ResourcesVector.size(); ++i)
			{
				CHECKED_DELETE(m_ResourcesVector[i]);
			}
			m_ResourcesVector.clear();
			m_ResourcesMap.clear();

		}
		TMapResources & GetResourcesMap()
		{
			return m_ResourcesMap;
		}
		TVectorResources & GetResourcesVector()
		{
			return m_ResourcesVector;
		}
};
#endif